<template>
  <el-container>
    <!-- 顶部查询栏 -->
    <el-header style="margin-top: 20px;width:20%;margin-left: 41%;">
      <el-input
          v-model="queryParams.name"
          placeholder="输入商品名称进行模糊查询"
          @input="handleSearch"
          clearable
      >
        <template #append>
          <el-button style="background-color: #30d104;color: white;" @click="handleSearch">搜索</el-button>
        </template>
      </el-input>
    </el-header>

    <!-- 筛选条件按钮 -->
    <el-main style="margin-left: 25%; margin-top: -2%;">
      <div class="filter-section">
        <!-- 分类筛选 -->
        <div class="filter-row">
          <span class="filter-label">分类</span>
          <el-button-group>
            <el-button
                v-for="category in categories"
                :key="category.id"
                :type="queryParams.categoryId === category.id ? 'primary' : 'default'"
                @click="applyFilter('categoryId', category.id)"
            >
              {{ category.name }}
            </el-button>
          </el-button-group>
        </div>

        <!-- 价格筛选 -->
        <div class="filter-row">
          <span class="filter-label">价格</span>
          <el-button-group>
            <el-button
                v-for="price in priceRanges"
                :key="price.value"
                :type="queryParams.price === price.value ? 'primary' : 'default'"
                @click="applyFilter('price', price.value)"
            >
              {{ price.label }}
            </el-button>
          </el-button-group>
        </div>

        <!-- 排序条件 -->
        <div class="filter-row">
          <span class="filter-label">排序</span>
          <el-button-group>
            <el-button
                v-for="sort in sortOptions"
                :key="sort.value"
                :type="queryParams.order === sort.value && queryParams.sort === 'ASC' ? 'primary' : 'default'"
                @click="toggleSortOrder(sort.value)"
            >
              {{ sort.label }} {{ queryParams.order === sort.value ? (queryParams.sort === 'ASC' ? '↑' : '↓') : '' }}
            </el-button>
          </el-button-group>
        </div>
      </div>
    </el-main>

    <!-- 商品展示 -->
    <el-row :gutter="20" style="width: 90%;margin-left: 6%;">
      <el-col :span="6" v-for="(product, index) in products" :key="index">
        <el-card style="margin-top: 10px;">
          <template v-if="product.userId === currentUserId">
            <el-tag type="success" style="position: relative; top: 10px; right: 10px;">我的</el-tag>
          </template>
          <template v-else>
            <el-tag type="info" style="position: relative; top: 10px; right: 10px;">他人</el-tag>
          </template>
          <img
              :src="product.image || defaultImage"
              class="product-image"
              alt="商品图片"
              @click="goToDetailPage(product.id)"
          />
          <div style="padding: 10px;">
            <p><span style="color: red;">￥</span><span style="color: red;font-size: 24px;">{{ product.price }}</span></p>
            <h4>{{ product.name }}</h4>
            <p class="price-text">{{ product.description }}</p>
            <div style="display:flex;">
                     <p>重量: {{ product.weight }}g</p>
              <p style="margin-left: 30%">库存: {{ product.nums }}</p>



            </div>
            <div style="display:flex;" >
              <div style="margin-top: 3.2px">
                <img style="width: 18px;height: 18px;position: relative;" src="@/assets/Photo/积分.png" alt="积分图标" />
              </div>

              <p style="margin-left: 4px">{{ product.point }}</p>
            </div>
          </div>
          <el-button style="margin-left: 6%" type="primary" @click="gotoBuy(product.id,product.userId)">我要购买</el-button>
          <el-button @click="handleAddToCart(product)">加入购物车</el-button>
        </el-card>
      </el-col>
    </el-row>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        layout="prev, pager, next"
        :total="totalItems"
        @current-change="handlePageChange"
        style="margin-left: 27%;margin-top: 20px;"
    />
  </el-container>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getGoodsListAPI, getCategoryListAPI ,addCartAPI} from '@/api/Goods.js';

import router from '@/router/index.js';
import { useUserStore } from '@/stores/user.js';
import {ElMessage} from "element-plus";

const store = useUserStore();
const currentUserId = store.UserId;

const queryParams = ref({
  pageNum: 1,
  pageSize: 12,
  name: '',
  categoryId: null,
  price: null,
  order: '',
  sort: 'ASC',  // Default to ascending order
  type: 1
});

const categories = ref([{ name: '全部', id: null }]);

const getCategoryList = async () => {
  try {
    const response = await getCategoryListAPI(1);
    if (response.data.code === 200) {
      categories.value = [{ name: '全部', id: null }, ...response.data.data];
    } else {
      console.error('获取分类失败：' + response.data.msg);
    }
  } catch (error) {
    console.error('获取分类失败：' + error.message);
  }
};

const priceRanges = ref([
  { label: '全部', value: null },
  { label: '10元以下', value: 10 },
  { label: '50元以下', value: 50 },
  { label: '100元以下', value: 100 },
  { label: '200元以下', value: 200 },
  { label: '500元以下', value: 500 },
  { label: '501元以上', value: 501 }
]);

const sortOptions = ref([
    {label: '默认', value: 'id'},
  {label: '价格', value: 'price'},
  {label: '重量', value: 'weight'},
  {label: '积分', value: 'point'},
  {label: '创建时间', value: 'create_time'},
  {label: '环保系数', value: 'ep_factor'}
]);

const products = ref([]);
const totalItems = ref(0);
const defaultImage = 'https://via.placeholder.com/150';

const handleSearch = async () => {
  try {
    const response = await getGoodsListAPI(queryParams.value);
    if (response.data.code === 200) {
      products.value = response.data.data.rows;
      totalItems.value = response.data.data.total;
    } else {
      console.error('查询商品失败:', response.msg);
    }
  } catch (error) {
    console.error('查询商品失败:', error);
  }
};

const applyFilter = (key, value) => {
  queryParams.value[key] = value;
  handleSearch();
};

const toggleSortOrder = (field) => {
  if (queryParams.value.order === field) {
    queryParams.value.sort = queryParams.value.sort === 'ASC' ? 'DESC' : 'ASC';
  } else {
    queryParams.value.order = field;
    queryParams.value.sort = 'ASC'; // Default to ASC when switching fields
  }
  handleSearch();
};

const goToDetailPage = (productId) => {
  router.push({path: '/product', query: {productId}});
};

//跳转到购买页面
const gotoBuy = (goodsId,sellerId) => {
  if (sellerId === store.UserId) {
    ElMessage.error("不能购买自己的商品");
    return;
  }
  router.push({
    path: '/buy',
    query: {
      productId: goodsId // Product ID
    }
  });
};


const handleAddToCart = (product) => {
  const cartData = {
    userId: store.UserId, // Current user's ID
    sellerId: product.userId, // Seller's ID
    goodsId: product.id, // Product ID
    categoryId: product.categoryId, // Product category ID
    image: product.image, // Use the first product image for the cart
    name: product.name, // Product name
    description: product.description, // Product description
    price: product.price, // Product price
    nums: 1, // Selected quantity
    type: product.type
  };

  if(cartData.userId===cartData.sellerId){
    ElMessage.error('不能购买自己的商品');
    return
  }

   addCartAPI(cartData).then(response=>{
     if(response.data.code===200){
       ElMessage.success('添加购物车成功');
     }else{
       ElMessage.error('添加购物车失败');
     }
   })



};

const handlePageChange = (newPage) => {
  queryParams.value.pageNum = newPage;
  handleSearch();
};

onMounted(() => {
  getCategoryList();
  handleSearch();
});
</script>

<style scoped>
.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-row {
  margin-bottom: 10px;
}

.filter-label {
  display: inline-block;
  width: 50px;
  font-weight: bold;
  margin-right: 10px;
}

.price-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 12px;
  color: #666;
}

.el-tag {
  position: absolute;
  top: 10px;
  right: 10px;
}
</style>
